package com.github.thinwonton.activemq.showcase.sample.deliverymode.queue;

import com.github.thinwonton.activemq.showcase.sample.utils.ActiveMQManager;

import javax.jms.*;

public class Producer {
    public static final String QUEUE_NAME = "test-deliverymode-queue";

    public static void main(String[] args) {
        System.out.println("Producer started!");

        //构建非持久消息和持久消息的内容
        String non_persistent_message_global = "全局方式设置的非持久消息 : " + System.currentTimeMillis();
        String persistent_message_global = "全局方式设置的持久消息 : " + System.currentTimeMillis();
        String persistent_message_single = "针对单条消息设置的持久消息 : " + System.currentTimeMillis();

        try {
            Connection connection = ActiveMQManager.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

            Queue queue = session.createQueue(QUEUE_NAME);
            MessageProducer producer = session.createProducer(queue);

            //发送一个持久信息
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage message1 = session.createTextMessage(persistent_message_global);
            producer.send(message1);

            //发送一个非持久信息
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            TextMessage message2 = session.createTextMessage(non_persistent_message_global);
            producer.send(message2);

            //发送一个持久信息
            TextMessage message3 = session.createTextMessage(persistent_message_single);
            message3.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            producer.send(message3);

            System.out.println("成功发送消息：" + message1.getText());
            System.out.println("成功发送消息：" + message2.getText());
            System.out.println("成功发送消息：" + message3.getText());

            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Producer end!");
    }
}
